<template>
    <div class="app-container h-100">
        <el-container class="h-100">
            <el-aside width="300px" style="background: #FFFFFF;">
                <leftTree @tree-check-change="treecheckchange" isDefault :leftlabel="'河流'" :apiType="'segmentRiverTree'" :regionApiParms="regionApiParms" :apiParms="{segmentType:'IsManual',segmentTypeDrink:'show'}"></leftTree>
            </el-aside>
             <el-container class="h-100">
                <el-header>
                    <!-- 数据类型选择 -->
                    <el-form :inline="true" class="demo-form-inline" size="small">
                        <!-- <el-form-item label="数据类型：">
                        <el-select v-model="dataType" placeholder="请选择">
                            <el-option label="月数据" value="month"></el-option>
                            <el-option label="日数据" value="day"></el-option>
                        </el-select>
                        </el-form-item> -->

                        <!-- 时间范围选择 -->
                        <el-form-item label="时间范围：">
                        <el-date-picker
                            v-model="dateRange"
                            type="monthrange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM"
                            format="yyyy-MM"
                        ></el-date-picker>
                        </el-form-item>

                        <!-- 监测因子选择 -->
                        <el-form-item label="监测因子：">
                        <el-select v-model="monitoringFactor" placeholder="请选择" multiple collapse-tags>
                            <!-- <el-option :label="'全选'" :value="'全选'"></el-option> -->
                            <el-option  v-for="item in bussinessItemList" :key="item.id" :label="item.itemName" :value="item.itemCode"></el-option>
                        </el-select>
                        </el-form-item>

                        <!-- 按钮组 -->
                        <el-form-item>
                            <!-- <el-radio-group v-model="btntype">
                                <el-radio-button label="原始数据" @click="handleOriginalData"></el-radio-button>
                                <el-radio-button label="审核数据" @click="handleReviewData"></el-radio-button>
                            </el-radio-group> -->
                            <el-button class="ml-5" type="primary" @click="handleQuery">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-header>
                <el-main class="h-100">
                    <div class="chart-box h-100">
                        <div ref="staticChart" id="staticChart"  style="height: 100%; width: 100%"></div>
                    </div>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>
<script> 
import * as echarts from "echarts";
import leftTree from '../../dataResources/waterJcData/monitor/sgMonitor/components/leftTree.vue'; 
import { bussinessItemData ,getManualTendency} from './api'
export default {
    components: {
        leftTree
    },
    data() {
        return {
            dataType: 'month',
            btntype:'原始数据',
            dateRange: [],
            monitoringFactor: [],
            bussinessItemList:[],
            queryParams:{
                segmentId:'',
                itemCode:'',
                beginTime:'',
                endTime:'',
            },
            regionApiParms:{
                segmentTypeDrink:'show',
                segmentType:'IsManual'
            },
            dyname:'',
            echartInit:false,
        }
    },
    created() {
        this.dateRange = [$moment().offset('month',-6).format(`{yyyy}-{mm}`),$moment().format(`{yyyy}-{mm}`)]
        this.getYzList()
    },
    mounted() {
        this.echartInit = echarts.init(this.$refs.staticChart);
        window.addEventListener("resize",  () => {
            this.echartInit.resize();
        });
    },
    methods: {
        async getYzList(){
            let params = {bussinessCategoryCode:'CBF8'};
            let res = await bussinessItemData(params)
            if (res.code == 200) {
                this.bussinessItemList = res.data || [];
                for(let i =0;i<4;i++) {
                    if(this.bussinessItemList[i]){
                        this.monitoringFactor.push(this.bussinessItemList[i].itemCode)
                    }
                }
            }
            setTimeout(() => {
                this.getlistData();
            }, 1000);
        },
        async getlistData(){
            this.queryParams.beginTime = this.dateRange[0];
            this.queryParams.endTime = this.dateRange[1];
            this.queryParams.itemCode = this.monitoringFactor.join(',');
            let res = await getManualTendency(this.queryParams)
            this.setEchartData(res.data);
        },
        treecheckchange(data){
            console.log('data: ', data);
            let ids = [];
            let names = [];
            for(let item of data){
                if(!item.children || item.children.length == 0) {
                    ids.push(item.id);
                    names.push(item.name)
                }
            }
            this.dyname = names.join(',');
            this.queryParams.segmentId = ids.join(',');
            
            
        },
        handleQuery() {
            this.getlistData();
            console.log('查询')
        },
        setEchartData(data){
            const leftYAxisStyle = {
                axisLine: { show: true, lineStyle: { color: "#666" } },
                axisTick: { show: true },
                splitLine: {
                show: true,
                lineStyle: { color: "#eee", type: "dashed" },
                },
            };

            const rightYAxisStyle = {
                axisLine: { show: true, lineStyle: { color: "#999" } },
                axisTick: { show: true },
                splitLine: { show: false },
            };
            // let legend_data = data.itemList.map(item => item.itemName);
            let xAxis_data = [];
            let nextMonth = this.dateRange[0];
            let endMonth = this.dateRange[1];
            let num = 0;

            while(nextMonth != endMonth && num < 100) {
                xAxis_data.push(nextMonth)
                num++
                nextMonth = $moment(nextMonth+'-01').offset('month',1).format(`{yyyy}-{mm}`);
                console.log('nextMonth: ', nextMonth);
            }
            xAxis_data.push(endMonth)
            let color = ['#FFB64D','#4895EF','#36CFC9','#FF7A45','#F08080','#BC8F8F','#6A5ACD','#FFD700','#90EE90','#9370DB']
            let leftYAxis = [];
            let rightYAxis = [];
            let legend_data = [];
            let itemMap = {};
            let zjNum = Math.floor(data.itemList.length/2);
            for(let i=0;i<zjNum;i++){
                legend_data.push(data.itemList[i].itemName);
                itemMap[data.itemList[i].itemCode+'_value'] = data.itemList[i];
                itemMap[data.itemList[i].itemCode+'_value']['color'] = color[i%10]
                itemMap[data.itemList[i].itemCode+'_value']['max'] = 0
                leftYAxis.push({
                    ...leftYAxisStyle,
                    type: "value",
                    name: `${data.itemList[i].itemName}`,
                    nameLocation: 'end',
                    nameTextStyle: { color: color[i%10],fontSize: 12 },
                    axisLabel: { 
                        formatter:`{value} ${data.itemList[i].unit || ''}`,
                        color: color[i%10],
                        fontSize: 10
                    },
                    "axisTick": { "show": true },
                    "min":0,
                    "max":1,
                    position: "left",
                    offset: 50*i,
                })
            }
            for(let r =zjNum;r<data.itemList.length;r++ ){
                legend_data.push(data.itemList[r].itemName);
                itemMap[data.itemList[r].itemCode+'_value'] = data.itemList[r];
                itemMap[data.itemList[r].itemCode+'_value']['color'] = color[r%10]
                itemMap[data.itemList[r].itemCode+'_value']['max'] = 0
                rightYAxis.push({
                    ...rightYAxisStyle,
                    type: "value",
                    name: `${data.itemList[r].itemName}`,
                    nameLocation: 'end',
                    nameTextStyle: { color: color[r%10] ,fontSize: 12},
                    axisLabel: { 
                        formatter:`{value} ${data.itemList[r].unit || ''}`,
                        color: color[r%10],
                        fontSize: 10
                    },
                    "axisTick": { "show": true },
                    "min":0,
                    "max":1,
                    position: "right",
                    offset: 50*(r-zjNum),
                })
            }
            let series = [];
            let yAxis = [...leftYAxis, ...rightYAxis]
            let seriesDataMap = {};
            let yAxisIndex = 0;
            for(let item of data.retList){
                for(let key in item) {
                    if(itemMap[key]){
                        if(!seriesDataMap[key]){
                            let yAxisIndex =  yAxis.findIndex(item => item.name == itemMap[key].itemName);
                            seriesDataMap[key] = {
                                name: itemMap[key].itemName,
                                type: "line",
                                data: [],
                                yAxisIndex: yAxisIndex,
                                itemStyle: { color: itemMap[key].color },
                                lineStyle: { width: 2 },
                                markPoint: {
                                    data: [],
                                    symbolSize: 60,
                                },
                            };
                        }
                        let keyData = item[key] || 0;
                        if(Number(keyData)> Number(itemMap[key].max)){
                            itemMap[key].max = keyData;
                            itemMap[key].maxXAxis = item.month;
                        }
                        seriesDataMap[key].data.push(item[key] || 0);
                        seriesDataMap[key].markPoint = {
                            data: [{ name: "峰值", value: itemMap[key].max, xAxis: itemMap[key].maxXAxis || xAxis_data[0], yAxis: itemMap[key].max }],
                            symbolSize: 60, 
                        }
                    }
                }
            }
            for(let nameLlis of data.itemList){
                if(seriesDataMap[nameLlis.itemCode+'_value']){
                    let item = seriesDataMap[nameLlis.itemCode+'_value'];
                    let yAxisIndex = item.yAxisIndex;
                    let max = item.markPoint.data[0] && item.markPoint.data[0].value || 1;;
                    console.log('max: ',  max);
                    yAxis[yAxisIndex].max = Math.ceil(max);
                    series.push(seriesDataMap[nameLlis.itemCode+'_value'])
                }
            }
            let options = {
                title: {
                    // text: `${this.dyname}断面变化趋势分析图`,
                    text: "水源地断面变化趋势分析图",
                    left: "center",
                    textStyle: { fontSize: 16 },
                },
                tooltip: {
                trigger: "axis",
                axisPointer: { type: "cross" },
                backgroundColor: "rgba(255, 255, 255, 0.9)",
                borderColor: "#ddd",
                borderWidth: 1,
                textStyle: { color: "#333" },
                formatter: (params) => {
                    let result = params[0].name + '<br/>';
                    params.forEach(param => {
                        const seriesItem = data.itemList.find(item => item.itemName === param.seriesName);
                        const unit = seriesItem ? seriesItem.unit : '';
                        result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>`;
                        result += `${param.seriesName}: ${param.value} ${unit}<br/>`;
                    });
                    return result;
                }
                },
                legend: {
                    data: legend_data,
                    type: "scroll",
                    left: 10,
                    top: 30,
                    textStyle: { fontSize: 12 },
                },
                grid: {
                // left: "15%",
                // right: "15%",
                // bottom: "10%",
                    top: "15%",
                    containLabel: true,
                },
                xAxis: {
                type: "category",
                data: xAxis_data,
                axisLabel: {
                    rotate: 45,
                    interval: 0,
                    fontSize: 10,
                },
                axisLine: { show: true },
                splitLine: { show: false },
                },
                yAxis:yAxis,
                series:series
            }
            console.log('options: ', options);
            // this.echartInit = echarts.init(this.$refs.staticChart);
            this.echartInit.setOption(options,true);
            // window.addEventListener("resize", function () {
            //     this.echartInit.resize();
            // });
        }
    }
}
</script>